package com.ruoyi.system.service.impl.wechat;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.text.csv.CsvUtil;
import cn.hutool.core.text.csv.CsvWriter;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.domain.entity.wechat.*;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.enums.wechat.ProblemStatus;
import com.ruoyi.common.enums.wechat.WechatRectificationStatusEnum;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.exception.user.UserException;
import com.ruoyi.system.domain.wechat.request.vo.*;
import com.ruoyi.system.mapper.wechat.*;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysDictTypeService;
import com.ruoyi.system.service.wechat.IWechatInspectionProblemService;
import com.ruoyi.system.service.wechat.IWechatUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 巡检问题
 *
 * @author jiexiang.sun/Jason
 * @version 1.0.0
 * @create 2022-03-04 0:07
 **/
@Service
@Slf4j
public class WechatInspectionProblemServiceImpl extends ServiceImpl<WechatInspectionProblemMapper, WechatInspectionProblem> implements IWechatInspectionProblemService {

    @Autowired
    private IWechatUserService wechatUserService;

    @Autowired
    private WechatInspectionProblemMapper wechatInspectionProblemMapper;

    @Autowired
    private WechatTaskProblemMapper wechatTaskProblemMapper;

    @Autowired
    private WechatDeptMapper wechatDeptMapper;

    @Autowired
    private WechatProblemPublishInfoMapper wechatProblemPublishInfoMapper;

    @Autowired
    private WechatInspectionProblemRectificationRecordsMapper wechatInspectionProblemRectificationRecordsMapper;

    @Autowired
    private ISysDictTypeService dictTypeService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private WechatTaskMapper taskMapper;

    @Autowired
    private ISysDeptService deptService;

    @Value("${wechat.problem.picture_path}")
    private String problemPicturePath;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean report(WechatInspectionProblemReportVO inspectionProblem) {
        Long problemId = IdUtil.getSnowflakeNextId();
        WechatInspectionProblem wechatInspectionProblem = new WechatInspectionProblem();
        BeanUtil.copyProperties(inspectionProblem, wechatInspectionProblem);
        wechatInspectionProblem.setId(problemId);
        wechatInspectionProblem.setOriginProblemId(problemId);
        wechatInspectionProblem.setLinkedProblemId(StrUtil.toString(problemId));
        wechatInspectionProblem.setReportTime(DateUtil.date());
        wechatInspectionProblemMapper.insert(wechatInspectionProblem);

        if (inspectionProblem.getReportUserRoleId().equals(4L) && null != inspectionProblem.getTaskId()) {
            WechatTaskProblem taskProblem = new WechatTaskProblem();
            taskProblem.setProblemId(problemId);
            taskProblem.setTaskId(inspectionProblem.getTaskId());
            wechatTaskProblemMapper.insert(taskProblem);
        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean review(WechatInspectionProblemReviewVO inspectionProblem) {
        LambdaQueryWrapper<WechatInspectionProblem> problemQW = new LambdaQueryWrapper<>();
        problemQW.eq(WechatInspectionProblem::getId, inspectionProblem.getProblemId())
                .eq(WechatInspectionProblem::getStatus, ProblemStatus.OK.getCode());
        WechatInspectionProblem problem = getOne(problemQW);

        if (ObjectUtil.isNull(problem)) {
            throw new UserException("wechat.problem.not.exists", null);
        }

        if (!problem.getRectificationStatus().equals(WechatRectificationStatusEnum.PROCESSING_COMPLETE.getStatus())) {
            throw new UserException("wechat.problem.not.completed", null);
        }

        WechatTask task = taskMapper.selectById(inspectionProblem.getTaskId());
        if (ObjectUtil.isNull(task)) {
            throw new UserException("wechat.task.not.exist", null);
        }

        Long problemId = IdUtil.getSnowflakeNextId();

        WechatInspectionProblem wechatInspectionProblem = new WechatInspectionProblem();
        BeanUtil.copyProperties(problem, wechatInspectionProblem);
        wechatInspectionProblem.setId(problemId);
        wechatInspectionProblem.setOriginProblemId(problem.getId());
        wechatInspectionProblem.setLinkedProblemId(StrUtil.join(",", problem.getLinkedProblemId(), problemId));
        wechatInspectionProblem.setReportUserId(inspectionProblem.getReportUserId());
        wechatInspectionProblem.setReportUserRoleId(inspectionProblem.getReportUserRoleId());
        wechatInspectionProblem.setReportUserDeptId(inspectionProblem.getReportUserDeptId());
        wechatInspectionProblem.setReportTime(DateUtil.date());
        wechatInspectionProblem.setRectificationStatus(WechatRectificationStatusEnum.NOT_PROCESSED.getStatus());
        wechatInspectionProblemMapper.insert(wechatInspectionProblem);

        WechatTaskProblem taskProblem = new WechatTaskProblem();
        taskProblem.setProblemId(problemId);
        taskProblem.setTaskId(inspectionProblem.getTaskId());
        wechatTaskProblemMapper.insert(taskProblem);
        return true;
    }

    @Override
    public List<WechatInspectionProblemListVO> getAllList(FilterForWechatInspectionProblemListVO params) {
        List<WechatInspectionProblem> wechatInspectionProblems = wechatInspectionProblemMapper.getAllList(params);
        return getWechatInspectionProblemListVOS(wechatInspectionProblems);
    }

    @Override
    public List<WechatInspectionProblemListVO> getByOtherTask(FilterForWechatInspectionProblemListVO params) {
        PageHelper.startPage(params.getPageNum(), params.getPageSize());
        List<WechatInspectionProblem> wechatInspectionProblems = wechatInspectionProblemMapper.getByOtherTask(params);
        return getWechatInspectionProblemListVOS(wechatInspectionProblems);
    }

    @Override
    public Integer statisticsProblemCount(FilterForWechatInspectionProblemListVO params) {
        return wechatInspectionProblemMapper.selectListCountByFilterParams(params);
    }

    @Override
    public List<Map<String, Object>> statisticsByProblemToArea(FilterForWechatInspectionProblemListVO params) {
        return wechatInspectionProblemMapper.statisticsByProblemToArea(params);
    }

    @Override
    public List<Map<String, Object>> statisticsByProblemToStreet(FilterForWechatInspectionProblemListVO params) {
        return wechatInspectionProblemMapper.statisticsByProblemToStreet(params);
    }

    @Override
    public List<Map<String, Object>> statisticsByProblemTypeToArea(FilterForWechatInspectionProblemListVO params) {
        return wechatInspectionProblemMapper.statisticsByProblemTypeToStreet(params);
    }

    @Override
    public List<Map<String, Object>> statisticsByProblemTypeToStreet(FilterForWechatInspectionProblemListVO params) {
        return wechatInspectionProblemMapper.statisticsByProblemTypeToStreet(params);
    }

    @Override
    public List<WechatInspectionProblemListVO> getList(FilterForWechatInspectionProblemListVO params) {
        PageHelper.startPage(params.getPageNum(), params.getPageSize());
        List<WechatInspectionProblem> wechatInspectionProblems = wechatInspectionProblemMapper.selectListByFilterParams(params);
        List<WechatInspectionProblemListVO> result = getWechatInspectionProblemListVOS(wechatInspectionProblems);
        return fillingProcessInfo(result);
    }

    @Override
    public Integer statisticsApprovalCount(FilterForWechatInspectionProblemListVO params) {
        return wechatInspectionProblemMapper.selectCountByApproval(params);
    }

    @Override
    public List<WechatInspectionProblemListVO> getApprovalList(FilterForWechatInspectionProblemListVO params) {
        PageHelper.startPage(params.getPageNum(), params.getPageSize());
        List<WechatInspectionProblem> wechatInspectionProblems = wechatInspectionProblemMapper.getApprovalList(params);
        if (CollectionUtil.isEmpty(wechatInspectionProblems)) {
            return Collections.EMPTY_LIST;
        }

        List<SysDictData> data = dictTypeService.selectDictDataByType("wechat_problem_category");
        if (CollectionUtil.isEmpty(data)) {
            data = Collections.EMPTY_LIST;
        }

        List<SysDictData> finalData = data;
        return wechatInspectionProblems.stream().map(p -> {
            WechatInspectionProblemListVO vo = new WechatInspectionProblemListVO();
            BeanUtil.copyProperties(p, vo);
            vo.setRectificationStatusDesc(WechatRectificationStatusEnum.getByStatus(vo.getRectificationStatus()).getDesc());
            vo.setProblemCategoryDesc(finalData.stream().filter(dict -> vo.getProblemCategory().equals(dict.getDictValue())).findFirst().get().getDictLabel());
            return vo;
        }).collect(Collectors.toList());
    }

    @Override
    public Integer statisticsProblemWorkOrderCount(FilterForWechatInspectionProblemListVO params) {
        return wechatInspectionProblemMapper.selectCountByWorkOrderList(params);
    }

    @Override
    public List<WechatInspectionProblemListVO> getWorkOrderList(FilterForWechatInspectionProblemListVO params) {
        PageHelper.startPage(params.getPageNum(), params.getPageSize());
        List<WechatInspectionProblem> wechatInspectionProblems = wechatInspectionProblemMapper.selectWorkOrderList(params);
        if (CollectionUtil.isEmpty(wechatInspectionProblems)) {
            return Collections.EMPTY_LIST;
        }

        List<SysDictData> data = dictTypeService.selectDictDataByType("wechat_problem_category");
        if (CollectionUtil.isEmpty(data)) {
            data = Collections.EMPTY_LIST;
        }

        List<SysDictData> finalData = data;
        return wechatInspectionProblems.stream().map(p -> {
            WechatInspectionProblemListVO vo = new WechatInspectionProblemListVO();
            BeanUtil.copyProperties(p, vo);
            vo.setRectificationStatusDesc(WechatRectificationStatusEnum.getByStatus(vo.getRectificationStatus()).getDesc());
            vo.setProblemCategoryDesc(finalData.stream().filter(dict -> vo.getProblemCategory().equals(dict.getDictValue())).findFirst().get().getDictLabel());
            return vo;
        }).collect(Collectors.toList());
    }

    @Override
    public List<WechatInspectionProblemInfoVO> getInfo(String problemId) {
        List<WechatInspectionProblem> problems = wechatInspectionProblemMapper.getLinkedListForInfo(problemId);

        if (CollectionUtil.isEmpty(problems)) {
            log.info("问题已经被删除或者不存在数据");
            return null;
        }

        return problems.stream().map(p -> {
            WechatInspectionProblemInfoVO vo = new WechatInspectionProblemInfoVO();
            BeanUtil.copyProperties(p, vo);

            LambdaQueryWrapper<WechatUser> userQW = new LambdaQueryWrapper<>();
            userQW.eq(WechatUser::getUserId, vo.getReportUserId());
            WechatUser user = wechatUserService.getOne(userQW);
            vo.setReportUserName(user.getName());

            List<SysDictData> data = dictTypeService.selectDictDataByType("wechat_problem_category");
            if (CollectionUtil.isEmpty(data)) {
                data = Collections.EMPTY_LIST;
            }

            vo.setProblemCategoryDesc(data.stream().filter(dict -> vo.getProblemCategory().equals(dict.getDictValue())).findFirst().get().getDictLabel());
            vo.setRectificationStatusDesc(WechatRectificationStatusEnum.getByStatus(vo.getRectificationStatus()).getDesc());

            // 问题的整改可能会是多次记录，所以这里order by 时间降序 结合 limit 1，是为了获取最新的整改记录
            LambdaQueryWrapper<WechatInspectionProblemRectificationRecords> recordsQW = new LambdaQueryWrapper<>();
            recordsQW.eq(WechatInspectionProblemRectificationRecords::getProblemId, p.getId())
                    .orderByDesc(WechatInspectionProblemRectificationRecords::getRectificationTime)
                    .last("limit 1");

            WechatInspectionProblemRectificationRecords record = wechatInspectionProblemRectificationRecordsMapper.selectOne(recordsQW);

            if (ObjectUtil.isNotNull(record)) {
                userQW = new LambdaQueryWrapper<>();
                userQW.eq(WechatUser::getUserId, record.getRectificationUserId());
                user = wechatUserService.getOne(userQW);

                vo.setRectificationTime(record.getRectificationTime());
                vo.setRectificationUserId(record.getRectificationUserId());
                vo.setRectificationUserName(user.getName());
                vo.setRectificationPhoto(record.getRectificationPhoto());
            }
            return vo;
        }).collect(Collectors.toList());
    }

    @Override
    public boolean modify(Long userId, WechatInspectionProblemModifyVO inspectionProblem) {
        LambdaQueryWrapper<WechatInspectionProblem> problemQW = new LambdaQueryWrapper<>();
        problemQW.eq(WechatInspectionProblem::getId, inspectionProblem.getProblemId())
                .eq(WechatInspectionProblem::getStatus, ProblemStatus.OK.getCode());

        WechatInspectionProblem problem = getOne(problemQW);

        if (ObjectUtil.isNull(problem)) {
            log.info("问题已经删除或者不存在");
            throw new UserException("wechat.problem.not.exists", null);
        }

        if (!problem.getReportUserId().equals(userId)) {
            log.info("不能修改他人上报的问题，修改人：{}，待修改数据信息：{}", userId, problem);
            throw new UserException("wechat.problem.can.not.opeator.others", null);
        }

        WechatInspectionProblem wechatInspectionProblem = new WechatInspectionProblem();
        BeanUtil.copyProperties(inspectionProblem, wechatInspectionProblem);
        return wechatInspectionProblemMapper.update(wechatInspectionProblem, problemQW) > 0 ? true : false;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean publish(Long userId, Long userRoleId, String deptIds, String problemIds) {
        Set<Long> deptIdSet = Arrays.stream(deptIds.split(",")).map(String::trim).filter(d -> StrUtil.isNotBlank(d)).map(Long::parseLong).collect(Collectors.toSet());
        if (CollectionUtil.isEmpty(deptIdSet)) {
            log.info("巡检问题下发失败，因为没有选择下发部门，接口接收到的部门编号：{}", deptIds);
            return false;
        }

        Set<Long> problemIdSet = Arrays.stream(problemIds.split(",")).map(String::trim).filter(p -> StrUtil.isNotBlank(p)).map(Long::parseLong).collect(Collectors.toSet());
        if (CollectionUtil.isEmpty(problemIdSet)) {
            log.info("巡检问题下发失败，因为没有选择下发问题，接口接收到的问题编号：{}", problemIds);
            return false;
        }

        //检查问题：1.是否存在、2.是否未被下发处理
        LambdaQueryWrapper<WechatInspectionProblem> problemQW = new LambdaQueryWrapper<>();
        problemQW.in(WechatInspectionProblem::getId, problemIdSet)
                .eq(WechatInspectionProblem::getStatus, ProblemStatus.OK.getCode());

        if (userRoleId.longValue() == 1) {
            problemQW.in(WechatInspectionProblem::getRectificationStatus
                    , WechatRectificationStatusEnum.NOT_PROCESSED.getStatus());
        } else if (userRoleId.longValue() == 2) {
            problemQW.in(WechatInspectionProblem::getRectificationStatus
                    , WechatRectificationStatusEnum.NOT_PROCESSED.getStatus()
                    , WechatRectificationStatusEnum.PUBLISH_COUNTY.getStatus()
                    , WechatRectificationStatusEnum.HANDLING_RETURN_COUNTY.getStatus());
        }

        Long count = wechatInspectionProblemMapper.selectCount(problemQW);

        if (problemIdSet.size() != count) {
            log.info("巡检问题下发失败，因为选择的下发问题不存在，或者问题都已经被下发过：{}", problemIds);
            return false;
        }

        DateTime date = DateUtil.date();
        problemIdSet.forEach(p -> {
            deptIdSet.forEach(d -> {
                WechatProblemPublishInfo info = new WechatProblemPublishInfo();
                info.setProblemId(p);
                info.setDeptId(d);

                if (userRoleId.longValue() == 1) {
                    info.setRoleId(2L);
                } else if (userRoleId.longValue() == 2) {
                    info.setRoleId(3L);
                }
                info.setPublishUserId(userId);
                info.setPublishTime(date);
                wechatProblemPublishInfoMapper.insert(info);
            });
        });

        //将下发的问题 状态改为：已下发状态
        LambdaUpdateWrapper<WechatInspectionProblem> problemUW = new LambdaUpdateWrapper<>();
        problemUW.in(WechatInspectionProblem::getId, problemIdSet);

        WechatInspectionProblem update = new WechatInspectionProblem();
        if (userRoleId.longValue() == 1) {
            update.setRectificationStatus(WechatRectificationStatusEnum.PUBLISH_COUNTY.getStatus());
        } else if (userRoleId.longValue() == 2) {
            update.setRectificationStatus(WechatRectificationStatusEnum.PUBLISH_STREET.getStatus());
        }
        wechatInspectionProblemMapper.update(update, problemUW);

        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean rectification(Long userId, Long problemId, String problemPhoto) {
        //更新问题信息
        LambdaUpdateWrapper<WechatInspectionProblem> problemUW = new LambdaUpdateWrapper<>();
        problemUW.eq(WechatInspectionProblem::getId, problemId)
                .eq(WechatInspectionProblem::getStatus, ProblemStatus.OK.getCode())
                .in(WechatInspectionProblem::getRectificationStatus,
                        WechatRectificationStatusEnum.PUBLISH_STREET.getStatus(),
                        WechatRectificationStatusEnum.HANDLING_RETURN_STREET.getStatus());

        WechatInspectionProblem wechatInspectionProblem = new WechatInspectionProblem();
        wechatInspectionProblem.setRectificationStatus(WechatRectificationStatusEnum.PROCESSED.getStatus());
        int updateCount = wechatInspectionProblemMapper.update(wechatInspectionProblem, problemUW);
        if (updateCount <= 0) {
            log.info("巡检问题整改提交失败，因为问题不存在，或者已经被整改过，当前状态不允许重复整改：{}", problemId);
            return false;
        }

        DateTime date = DateUtil.date();
        WechatInspectionProblemRectificationRecords record = new WechatInspectionProblemRectificationRecords();
        record.setProblemId(problemId);
        record.setRectificationUserId(userId);
        record.setRectificationTime(date);
        record.setRectificationPhoto(problemPhoto);
        //新增整改记录
        wechatInspectionProblemRectificationRecordsMapper.insert(record);

        return true;
    }

    @Override
    public boolean audit(Long userId, Long problemId, short status) {
        LambdaUpdateWrapper<WechatInspectionProblem> problemUW = new LambdaUpdateWrapper<>();
        problemUW.eq(WechatInspectionProblem::getId, problemId)
                .eq(WechatInspectionProblem::getStatus, ProblemStatus.OK.getCode())
                .eq(WechatInspectionProblem::getRectificationStatus, WechatRectificationStatusEnum.PROCESSED.getStatus());

        WechatInspectionProblem wechatInspectionProblem = new WechatInspectionProblem();
        wechatInspectionProblem.setRectificationStatus(status);
        int updateCount = wechatInspectionProblemMapper.update(wechatInspectionProblem, problemUW);
        if (updateCount <= 0) {
            log.info("巡检问题整改审核失败，因为问题不存在，或者已经被退回/通过：{}", problemId);
            return false;
        }

        return true;
    }


    @Override
    public void export(FilterForWechatInspectionProblemListVO params, HttpServletResponse response) {
        String fileName = DateUtil.date().toDateStr();
        List<WechatInspectionProblemListVO> result = null;
        WechatTask task = taskMapper.selectById(params.getTaskId());
        if (ObjectUtil.isNotEmpty(task)) {
            fileName = task.getTaskName();

            List<WechatInspectionProblem> wechatInspectionProblems = wechatInspectionProblemMapper.selectListByFilterParams(params);
            if (CollectionUtil.isNotEmpty(wechatInspectionProblems)) {
                List<SysDictData> data = dictTypeService.selectDictDataByType("wechat_problem_category");
                if (CollectionUtil.isEmpty(data)) {
                    data = Collections.EMPTY_LIST;
                }

                List<SysDictData> finalData = data;
                result = wechatInspectionProblems.stream().map(p -> {
                    WechatInspectionProblemListVO vo = new WechatInspectionProblemListVO();
                    BeanUtil.copyProperties(p, vo);
                    vo.setRectificationStatusDesc(WechatRectificationStatusEnum.getByStatus(vo.getRectificationStatus()).getDesc());
                    vo.setProblemCategoryDesc(finalData.stream().filter(dict -> vo.getProblemCategory().equals(dict.getDictValue())).findFirst().get().getDictLabel());
                    return vo;
                }).collect(Collectors.toList());
            }
        }

        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".csv");
        response.setContentType("APPLICATION/OCTET-STREAM;charset=UTF-8");
        try (CsvWriter writer = CsvUtil.getWriter(response.getWriter());) {
            writer.writeLine("地点", "检查内容");
            if (CollectionUtil.isNotEmpty(result)) {
                result.forEach(r -> {
                    writer.writeLine(r.getAddress(), r.getProblemContent());
                });
            }
        } catch (IOException e) {
            e.printStackTrace();
            throw new GlobalException("任务导出失败：" + e.getMessage());
        }
    }

    /**
     * 填充处理人信息
     *
     * @param list
     * @return
     */
    private List<WechatInspectionProblemListVO> fillingProcessInfo(List<WechatInspectionProblemListVO> list) {
        if (CollectionUtil.isEmpty(list)) {
            return Collections.EMPTY_LIST;
        }

        list.stream().forEach(l -> {
            LambdaQueryWrapper<WechatProblemPublishInfo> qw = new LambdaQueryWrapper();
            qw.eq(WechatProblemPublishInfo::getProblemId, l.getId())
                    .orderByDesc(WechatProblemPublishInfo::getPublishTime)
                    .last("limit 1");
            WechatProblemPublishInfo info = wechatProblemPublishInfoMapper.selectOne(qw);
            if (ObjectUtil.isNull(info)) {
                return;
            }

            SysDept dept = deptService.selectDeptById(info.getDeptId());
            if (ObjectUtil.isNull(dept)) {
                return;
            }

            l.setProcessDeptName(dept.getDeptName());
        });

        return list;
    }

//
//    /**
//     * 填充处理人信息
//     *
//     * @param list
//     * @return
//     */
//    private List<WechatInspectionProblemListVO> fillingProcessInfo(List<WechatInspectionProblemListVO> list) {
//        if (CollectionUtil.isEmpty(list)) {
//            return Collections.EMPTY_LIST;
//        }
//
//        list.stream().forEach(l -> {
//            if (l.getRectificationStatus().shortValue() == WechatRectificationStatusEnum.NOT_PROCESSED.getStatus()) {
//                return;
//            }
//
//            //查询区县级部门信息，如果有多个处理部门，仅取1个
//            LambdaQueryWrapper<WechatProblemPublishInfo> qwArea = new LambdaQueryWrapper();
//            qwArea.eq(WechatProblemPublishInfo::getProblemId, l.getId())
//                    .eq(WechatProblemPublishInfo::getRoleId, 2)
//                    .orderByDesc(WechatProblemPublishInfo::getPublishTime)
//                    .last("limit 1");
//            WechatProblemPublishInfo areaInfo = wechatProblemPublishInfoMapper.selectOne(qwArea);
//            if (ObjectUtil.isNull(areaInfo)) {
//                return;
//            }
//
//            SysDept areaDept = deptService.selectDeptById(areaInfo.getDeptId());
//            if(ObjectUtil.isNull(areaDept)){
//                return ;
//            }
//
//            WechatProblemProcessInfoVO areaProcessInfo = new WechatProblemProcessInfoVO();
//            areaProcessInfo.setProcessDeptName(areaDept.getDeptName());
//            l.setAreaProcess(areaProcessInfo);
//
//            if (l.getRectificationStatus().shortValue() != WechatRectificationStatusEnum.PUBLISH_COUNTY.getStatus()) {
//                //查询街道级部门信息
//                //查询区县级部门信息，如果有多个处理部门，仅取1个
//                LambdaQueryWrapper<WechatProblemPublishInfo> qwStreet = new LambdaQueryWrapper();
//                qwStreet.eq(WechatProblemPublishInfo::getProblemId, l.getId())
//                        .eq(WechatProblemPublishInfo::getRoleId, 3)
//                        .orderByDesc(WechatProblemPublishInfo::getPublishTime)
//                        .last("limit 1");
//                WechatProblemPublishInfo streetInfo = wechatProblemPublishInfoMapper.selectOne(qwStreet);
//                if (ObjectUtil.isNull(streetInfo)) {
//                    return;
//                }
//
//                SysDept streetDept = deptService.selectDeptById(streetInfo.getDeptId());
//                if(ObjectUtil.isNull(streetDept)){
//                    return ;
//                }
//
//                WechatProblemProcessInfoVO streetProcessInfo = new WechatProblemProcessInfoVO();
//                streetProcessInfo.setProcessDeptName(streetDept.getDeptName());
//                l.setStreetProcess(streetProcessInfo);
//            }
//        });
//        return list;
//    }

    private List<WechatInspectionProblemListVO> getWechatInspectionProblemListVOS(List<WechatInspectionProblem> wechatInspectionProblems) {
        if (CollectionUtil.isEmpty(wechatInspectionProblems)) {
            return Collections.EMPTY_LIST;
        }

        List<SysDictData> data = dictTypeService.selectDictDataByType("wechat_problem_category");
        if (CollectionUtil.isEmpty(data)) {
            data = Collections.EMPTY_LIST;
        }

        List<SysDictData> finalData = data;
        return wechatInspectionProblems.stream().map(p -> {
            WechatInspectionProblemListVO vo = new WechatInspectionProblemListVO();
            BeanUtil.copyProperties(p, vo);
            vo.setRectificationStatusDesc(WechatRectificationStatusEnum.getByStatus(vo.getRectificationStatus()).getDesc());
            Optional<SysDictData> first = finalData.stream().filter(dict -> vo.getProblemCategory().equals(dict.getDictValue())).findFirst();
            if (first.isPresent()) {
                vo.setProblemCategoryDesc(first.get().getDictLabel());
            } else {
                log.info("巡检问题中的问题类型不在字典数据【wechat_problem_category】中，问题：{}", JSONUtil.toJsonStr(vo));
            }

            return vo;
        }).collect(Collectors.toList());
    }
}
